package org.pplb5.siresto;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;

//import com.actionbarsherlock.sample.demos.R;

public class ActivityUtama extends SherlockFragmentActivity implements
ActionBar.TabListener {
	//private TextView mSelected;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_Sherlock_Light);
		super.onCreate(savedInstanceState);

		setContentView(R.layout.menutama_view);
		// mSelected = (TextView) findViewById(R.id.text);

		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		String[] options = { "BERANDA", "DAFTAR RESTO", "DAFTAR PROMOSI" };
		for (int i = 1; i <= 3; i++) {
			ActionBar.Tab tab = getSupportActionBar().newTab();
			// tab.setText("Tab " + i);
			tab.setText(options[i - 1]);
			tab.setTabListener(this);
			getSupportActionBar().addTab(tab);
		}
		Toast.makeText(this, "Selamat Datang di SIResto!", Toast.LENGTH_SHORT).show();

	}

	public void onTabReselected(Tab tab, FragmentTransaction transaction) {

	}

	public void onTabSelected(Tab tab, FragmentTransaction transaction) {
		if (tab.getPosition() == 2) {
			transaction.replace(R.id.fragment_content,
					new DataPromosi());

		} else if (tab.getPosition() == 1) {
			transaction.replace(R.id.fragment_content,
					new DaftarRestoFragment(getApplicationContext()));

		} else {
			transaction.replace(R.id.fragment_content, new BerandaFragment());

		}

	}

	public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
	}
}

/*class PromosiDiskonFragment extends SherlockListFragment {
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		String[] values = new String[] { "Diskon A", "Diskon B", "Diskon C",
				"Diskon D", "Diskon E", "Diskon F", "Diskon G", "Diskon H",
				"Diskon I", "Diskon J","Diskon A", "Diskon B", "Diskon C",
				"Diskon D", "Diskon E", "Diskon F", "Diskon G", "Diskon H",
				"Diskon I", "Diskon J" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, values);
		setListAdapter(adapter);



	}
} */

class DataPromosi extends SherlockListFragment {



	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getDataPromosi();
	}

	protected void getDataPromosi() {
		String result = "";
		InputStream isr = null;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://annisadwinidia.hostei.com/getPromosi.php");
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			isr = entity.getContent();
		} catch(Exception e) {
			Log.e("log.log", "Error in http connection "+e.toString());
			//resultView.setText("Could not connect to database");
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null ){
				sb.append(line + "\n");
			}
			isr.close();

			result = sb.toString();

		} catch(Exception e) {
			Log.e("log.log", "Error converting result");

		}

		try {
			//String s = "";
			JSONArray jArray = new JSONArray(result);
			int n = jArray.length();
			String[] values = new String[n];

			for(int i = 0; i<n; i++){
				JSONObject json = jArray.getJSONObject(i);
				values[i] = json.getString("namaPromosi") + "\n" + "Keterangan: " + json.getString("keteranganPromosi") ;	
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
					android.R.layout.simple_list_item_1, values);
			setListAdapter(adapter);
			//resultView.setText(s);
		} catch(Exception e) {
			Log.e("log.log", "Error parsing data "+e.toString());
			Log.e("log.log", "Failed data was:\n" + result);
		}
	}

}



class DaftarRestoFragment extends SherlockListFragment {
	private Context c;
	public DaftarRestoFragment(Context c){
		this.c=c;
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		/*String[] values = new String[] { "Resto A", "Resto B", "Resto C",
				"Resto D", "Resto E", "Resto F", "Resto G", "Resto H",
				"Resto I", "Resto J" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				R.layout.daftarrestoran_view, R.id.resto_name, values);
		// Restoran[] resto = new Restoran[10];
		// for(int i=0;i<10;i++){
		// resto[i] = new Restoran("Resto "+i,"images/cube.jpg");
		// }
		// RestoAdapter adapter = new RestoAdapter(getActivity(),
		// R.layout.daftarrestoranview, resto);
		setListAdapter(adapter); */
		getDataRestoran();
		//getImageRestoran();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		String item = (String) getListAdapter().getItem(position);
		//Toast.makeText(getActivity(), item + " selected", Toast.LENGTH_SHORT).show();
		Intent i = new Intent(c, ActivityDetilRestoran.class);
		// sending data to new activity
		i.putExtra("NAMA_RESTO", item);
		startActivity(i);

	}

	protected void getDataRestoran() {
		String result = "";
		InputStream isr = null;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://annisadwinidia.hostei.com/getRestoran.php");
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			isr = entity.getContent();
		} catch(Exception e) {
			Log.e("log.log", "Error in http connection "+e.toString());
			//resultView.setText("Could not connect to database");
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null ){
				sb.append(line + "\n");
			}
			isr.close();

			result = sb.toString();

		} catch(Exception e) {
			Log.e("log.log", "Error converting result");

		}

		try {
			//String s = "";
			JSONArray jArray = new JSONArray(result);
			int n = jArray.length();
			String[] values = new String[n];

			for(int i = 0; i<n; i++){
				JSONObject json = jArray.getJSONObject(i);
				values[i] = json.getString("namaRestoran");	

			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
					R.layout.daftarrestoran_view, R.id.resto_name, values);
			setListAdapter(adapter);
			//resultView.setText(s);
		} catch(Exception e) {
			Log.e("log.log", "Error parsing data "+e.toString());
			Log.e("log.log", "Failed data was:\n" + result);
		}
	}


}

class BerandaFragment extends SherlockFragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.beranda_view, container, false);

		return v;
	}
}
// class PromoAdapter extends ArrayAdapter<Promosi> {
// private Context c;
// private Promosi[] p;
//
// public PromoAdapter(Context context, Promosi[] objects) {
// super(context, R.layout.daftarpromosi, objects);
// c = context;
// p = objects;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// LayoutInflater inflater = (LayoutInflater)
// c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View rowView = inflater.inflate(R.layout.daftarpromosi, parent, false);
// TextView namaView = (TextView) rowView.findViewById(R.id.namaPromosi);
// TextView ketView = (TextView) rowView.findViewById(R.id.keteranganPromosi);
// namaView.setText(p[position].getNama());
// ketView.setText(p[position].getKeterangan());
// return rowView;
// }
//
// }

// class PromoAdapter extends ArrayAdapter<Promosi> {
// private Context c;
// private Promosi[] p;
//
// public PromoAdapter(Context context, Promosi[] objects) {
// super(context, R.layout.daftarpromosi, objects);
// c = context;
// p = objects;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// LayoutInflater inflater = (LayoutInflater)
// c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View rowView = inflater.inflate(R.layout.daftarpromosi, parent, false);
// TextView namaView = (TextView) rowView.findViewById(R.id.namaPromosi);
// TextView ketView = (TextView) rowView.findViewById(R.id.keteranganPromosi);
// namaView.setText(p[position].getNama());
// ketView.setText(p[position].getKeterangan());
// return rowView;
// }
//
// }